package cn.e_eap.esite.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import sun.awt.shell.ShellFolder;

public class Utils {

	public static BufferedImage getFileIcon(File file, int w, int h)
			throws IOException {
		BufferedImage bi = null;
		if (file.isFile()) {
			bi=ImageIO.read(file);

			if (bi != null && bi.getWidth() >= 0 && bi.getHeight() >= 0) {
				Image scaledImage = null;
				if (bi.getWidth() > w && bi.getHeight() < bi.getWidth()) {
					scaledImage = bi.getScaledInstance(w, w * bi.getHeight()
							/ bi.getWidth(), BufferedImage.TYPE_INT_ARGB);
				} else if (bi.getHeight() > h && bi.getHeight() > bi.getWidth()) {
					scaledImage = bi.getScaledInstance(
							h * bi.getWidth() / bi.getHeight(), h,
							BufferedImage.TYPE_INT_ARGB);
				}
				if (scaledImage != null) {
					bi = new BufferedImage(scaledImage.getWidth(null),
							scaledImage.getHeight(null),
							BufferedImage.TYPE_INT_ARGB);
					bi.getGraphics().drawImage(scaledImage, 0, 0, w, h, null);
					bi.getGraphics().dispose();
				}
				return bi;
			} else {

				ShellFolder shellFolder = ShellFolder.getShellFolder(file);
				Image icon = shellFolder.getIcon(true);

				bi = new BufferedImage(icon.getWidth(null),
						icon.getHeight(null), BufferedImage.TYPE_INT_ARGB);
				bi.getGraphics().drawImage(icon, 0, 0, w, h, null);
				bi.getGraphics().dispose();
			}
		} else {
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("res/folder.png");
			if(in != null){
				bi = ImageIO.read(in);
			}
		}
		return bi;
	}
}
